package com.weiqiao.api.rest;


import com.google.zxing.WriterException;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.aop.log.Log;
import com.weiqiao.api.domain.*;
import com.weiqiao.api.domain.dto.LabelShelfApiEntityDTO;
import com.weiqiao.api.domain.vo.*;
import com.weiqiao.api.service.*;
import com.weiqiao.api.until.ApiResUtil;
import com.weiqiao.api.until.ImageUtil;
import com.weiqiao.api.until.config.WXConfig;
import com.weiqiao.config.ConstantProperties;
import com.weiqiao.utils.StringUtils;
import com.weiqiao.utils.WeiXinOssUtil;
import org.apache.commons.collections.map.HashedMap;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "mallApi/core/api")
public class CoreApiController {

    @Autowired
    private ICarouseApiService carouseService;

    @Autowired
    private IVarietyApiService varietyApiService;

    @Autowired
    private ILabelShelfApiService labelShelfApiService;

    @Autowired
    private IAppUserApiService appUserApiService;

    /**
     * 信用卡产品表
     */
    @Autowired
    private ICardCommodityApiService cardCommodityApiService;

    /**
     * 商品表
     */
    @Autowired
    private ICommodityApiService commodityApiService;

    /**
     * 根据轮播图id获取轮播图详情
     * 因为当前项目只有首页用到轮播图，所以默认取轮播图配置的第一条
     * 如有多个地方使用，该接口需要修改
     *
     * @param vo
     * @return
     */
    @Log("获取首页轮播图详情")
    @GetMapping("/carouse/carouse-detail")
    public ApiResponseEntity carouseDetail(@Validated CarouseEntityVO vo) {
        List<CarouseApiEntity> carouseList = carouseService.getCarouseList(vo);
        return ApiResUtil.buildRes(true, "首页轮播图", carouseList);
    }

    @Log("获取首页标签列表")
    @GetMapping("/variety/commodity-label/{company_id}")
    public ApiResponseEntity commodityLabelList(@PathVariable String company_id) {
        if (!StringUtil.isInteger(company_id)) {
            return ApiResUtil.buildRes(false, "公司id不能为空！");
        }
        // 此处不不考虑产品查询，产品查询用其他接口进行查询以便于分页查询
        List<LabelShelfApiEntityDTO> list = labelShelfApiService.commodityLabelList(company_id);
        return ApiResUtil.buildRes(true, "首页标签列表", list);
    }

    @Log("根据条件获得产品列表")
    @GetMapping("/commodity/card-commodity-list")
    public ApiResponseEntity getCardCommodityList(@Validated CardCommodityApiVO vo) {
        List<CardCommodityApiEntity> list = cardCommodityApiService.findCommoditys(vo);
        return ApiResUtil.buildRes(true, "产品列表", list);
    }

    @Log("获取产品分类列表")
    @GetMapping("/variety/commodity-variety/{company_id}")
    public ApiResponseEntity commodityVariety(@PathVariable String company_id) {
        if (!StringUtil.isInteger(company_id)) {
            return ApiResUtil.buildRes(false, "公司id不能为空！");
        }
        List<VarietyApiEntity> list = varietyApiService.getVarietyList(company_id);
        return ApiResUtil.buildRes(true, "产品分类列表", list);
    }

    @Log("根据条件获得积分商品列表")
    @GetMapping("/commodity/score-commodity-list")
    public ApiResponseEntity getScoreCommodityList(@Validated CommodityApiVO vo) {
        vo.setIs_score_commodity(1);
        List<CommodityApiEntity> list = commodityApiService.findCommodity(vo);
        return ApiResUtil.buildRes(true, "积分商品列表", list);
    }

    @Log("分享商品二维码")
    @GetMapping("/qrcode/compmodity-id")
    public ApiResponseEntity getCompmodityQRCode(@Validated QRCodeVO vo) throws IOException, WriterException {
        String URL = WXConfig.JUMP_H5_URL;
        boolean is_card_commodity = vo.getCommodity_type() == 0;
        String commodity_img = "";
        String commodity_id = "";
        String commodity_name = "";
        String commodity_tity = "";

        // 拼装内容的各个尺寸信息
        int commodity_img_height = is_card_commodity ? 250 : 400; // 银行卡高度 250,积分商品400
        int commodity_name_y = is_card_commodity ? 350 : 490; // 商品名称定位
        int commodity_tity_y = is_card_commodity ? 410 : 550; // 商品标题定位
        int qrcode_x = 340; // 二维码定位
        int font_height = 30; // 上下字间距

        /**
         * 商品二维码
         * 用户扫码之后跳转到指定的商品页面
         * 如果用户没有上级，则将邀请人绑定为其上级，并将团队id修改为邀请人的团队id
         */
        Integer company_id = vo.getCompany_id();
        Integer user_id = vo.getUser_id();
        // 参数校验
        if (StringUtil.isBlank(vo.getCommodity_id()) || StringUtil.isBlank(vo.getCommodity_type())) {
            return ApiResUtil.buildRes(false, "二维码生成失败，请检查参数");
        }
        // 获取用户信息
        AppUserApiEntity user = appUserApiService.getUser(company_id, Filters.eq("user_id", user_id));
        if (user == null) {
            return ApiResUtil.buildRes(false, "二维码生成失败，请检查用户信息");
        }
        // 判断用户角色，来决定返回的邀请人id
        int recomend_id = user.getMember_type() == 0 ? user.getRecommend_id() : user_id;
        if (is_card_commodity) {
            CardCommodityApiVO cardVo = new CardCommodityApiVO();
            cardVo.setCompany_id(company_id);
            cardVo.setCommodity_id(vo.getCommodity_id());
            CardCommodityApiEntity cardEntity = cardCommodityApiService.findCommodityDetail(cardVo);
            if (StringUtil.isBlank(cardEntity.getCommodity_id())) {
                return ApiResUtil.buildRes(false, "二维码生成失败，请检查商品信息");
            }
            commodity_id = cardEntity.getCommodity_id();
            commodity_img = getImage(cardEntity);
            commodity_name = cardEntity.getName();
            commodity_tity = cardEntity.getPro_title();
            URL += "pages/homepage/creditCard/details";
        } else {
            CommodityApiVO commodityVo = new CommodityApiVO();
            commodityVo.setCompany_id(company_id);
            commodityVo.setCommodity_id(vo.getCommodity_id());
            CommodityApiEntity commodityEntity = commodityApiService.findCommodityDetail(commodityVo);
            if (StringUtil.isBlank(commodityEntity.getCommodity_id())) {
                return ApiResUtil.buildRes(false, "二维码生成失败，请检查商品信息");
            }
            commodity_id = commodityEntity.getCommodity_id();
            commodity_img = getImage(commodityEntity);
            commodity_name = commodityEntity.getName();
            commodity_tity = commodityEntity.getPro_title();
            URL += "pages/mine/integral/details";
        }
        URL += "?param=0,"
                + recomend_id
                + "," + (StringUtil.isBlank(user.getTeam_id()) ? "*" : user.getTeam_id())
                + "," + vo.getCommodity_id();

        URL += is_card_commodity ? "" : ",1";
        String suffix = ".png";
        // 生成二维码
        String qrCodeFilePath = WXConfig.UPLOADFILE + "qrcode/" + user_id + suffix;
        ImageUtil.generateQRCodeImage(URL, 300, 300, qrCodeFilePath);

        // 1、背景地址
//        String path = WXConfig.UPLOADFILE + "qrcode/qrcodeBgi.png"; // 底图地址
//        File filePath = new File(path);
        String path = WXConfig.UPLOAD + "qrcode/qrcodeBgi.png"; // 底图地址
        InputStream filePath = ImageUtil.urlToIs(path);
        Image backgroundImg = ImageIO.read(filePath); // 背景图片 流

        // 2、背景 + 商品信息
        // 将服务器文件转流
        InputStream is = ImageUtil.urlToIs(commodity_img);
        // 2.1 背景 + 商品图
        Image commodity_qrcode_img = ImageUtil.upImgWidthAndHeight(ImageIO.read(is), commodity_img_height, 400);
        BufferedImage image = ImageUtil.pictureSynthesis(commodity_qrcode_img, backgroundImg, 30, 30);
        // 2.2 图片 + 商品价格 + 商品名
        String name = commodity_name.length() > 10 ? commodity_name.substring(0, 10) + "..." : commodity_name;
        image = ImageUtil.pictureAddText(name, image, "宋体", 0, Color.black, 30, 30, commodity_name_y); // 商品名
        // 2.3 商品副标题
        if (is_card_commodity) {
            /**
             * 如果是信用卡商品
             * 首先判断字体总数，是否超过 18*2
             * 如果字体超过没有超过 18*2 显示两行，二维码居中显示
             * 如果超过，显示规则为 12*5 二维码居右显示
             */
            int font_row_length = commodity_tity.length() > 36 ? 12 : 18;
            font_row_length = font_row_length > commodity_tity.length() ? commodity_tity.length() : font_row_length;
            qrcode_x = commodity_tity.length() > 36 ? qrcode_x : 180;
            do {
                String show_title = commodity_tity.substring(0, font_row_length);
                commodity_tity = commodity_tity.substring(font_row_length);
                image = ImageUtil.pictureAddText(show_title, image, "宋体", 0, Color.black, 22, 30, commodity_tity_y);
                commodity_tity_y += font_height;
            } while (commodity_tity.length() > font_row_length);
            if (commodity_tity.length() > 0) {
                image = ImageUtil.pictureAddText(commodity_tity, image, "宋体", 0, Color.black, 22, 30, commodity_tity_y);
            }
        } else {
            // 如果是积分商品，副标题拆分为12*2进行显示 最多显示两行
            commodity_tity = commodity_tity.length() > 12 ? commodity_tity.substring(0, 12) : commodity_tity;
            image = ImageUtil.pictureAddText(commodity_tity, image, "宋体", 0, Color.black, 22, 30, commodity_tity_y);
            if (commodity_tity.length() > 0) {
                commodity_tity_y += font_height;
                commodity_tity = commodity_tity.length() > 10 ? commodity_tity.substring(0, 10) + "..." : commodity_tity;
                image = ImageUtil.pictureAddText(commodity_tity, image, "宋体", 0, Color.black, 22, 30, commodity_tity_y);
            }
        }

        // 2.3 图片 + 二维码
        Image qrcodeImg = ImageUtil.upImgWidthAndHeight(ImageIO.read(new File(qrCodeFilePath)), 100, 100);
        image = ImageUtil.pictureSynthesis(qrcodeImg, image, qrcode_x, 460);
        // 2.3 扫描提示语
        image = ImageUtil.pictureAddText("扫一扫或", image, "宋体", 0, Color.black, 15, qrcode_x + 20, 570);   // 商品副标题
        image = ImageUtil.pictureAddText("长按识别二维码", image, "宋体", 0, Color.black, 15, qrcode_x - 10, 590);   // 商品副标题

        InputStream imageInput = null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, suffix, os);
            imageInput = new ByteArrayInputStream(os.toByteArray());
        } catch (IOException e) {
        }

        // 海报路径
        String poster = "qrcode" + File.separator + "poster";
        String posterPath = WXConfig.UPLOADFILE + poster;
        String poster_path_location = posterPath + File.separator + commodity_name + suffix;
        // 图片保存到本地
        ImageUtil.savePic(imageInput, posterPath, commodity_name + suffix);

        ImageIO.write(image, "png", new File(poster_path_location));

        // 将生成的海报上传到OSS
        String ossPath = "qrcode/" + (is_card_commodity ? "card_commmodity/" : "commmodity/") + (commodity_id + "_" + user_id) + suffix;
        WeiXinOssUtil.getWeiXinOssUtil().importFile(poster_path_location, ossPath);
        String resultPath = ConstantProperties.WQ_FILE_HOST + ossPath;

        // 删除本地 二维码 释放空间
        File d_qrcode_file = new File(qrCodeFilePath);
        d_qrcode_file.delete();
        // 删除本地 海报 释放空间
        File d_poster_file = new File(poster_path_location);
        d_poster_file.delete();
        return ApiResUtil.buildRes(true, "商品分享二维码", resultPath);
    }

    @Log("招募合伙人二维码")
    @GetMapping("/qrcode/my-share")
    public ApiResponseEntity getMyShareQRCode(@Validated QRCodeVO vo) throws IOException, WriterException {
        String URL = WXConfig.JUMP_H5_URL;
        /**
         * 招募合伙人
         * 用户扫码之后跳转到h5首页
         * 如果用户没有上级，则将邀请人绑定为其上级，并将团队id修改为邀请人的团队id
         * 修改用户等级角色 ：
         *        邀请人       扫码者角色
         *        省长            团长
         *        团长            分销员
         *        分销员          客户
         *        客户            客户
         */
        Integer company_id = vo.getCompany_id();
        Integer user_id = vo.getUser_id();
        // 获取用户信息
        AppUserApiEntity user = appUserApiService.getUser(company_id, Filters.eq("user_id", user_id));
        if (user == null) {
            return ApiResUtil.buildRes(false, "二维码生成失败，请检查用户信息");
        }
        // 判断用户角色，来决定返回的邀请人id
        int recomend_id = user.getMember_type() == 0 ? user.getRecommend_id() : user_id;
        URL += "pages/homepage/homepage?param=1,"
                + recomend_id
                + "," + (StringUtil.isBlank(user.getTeam_id()) ? "*" : user.getTeam_id());
        String suffix = ".PNG";
        // 生成二维码
        String qrcode_file_path = WXConfig.UPLOADFILE + "qrcode/" + user_id + suffix;
        ImageUtil.generateQRCodeImage(URL, 150, 150, qrcode_file_path);

        // 底图取自商城配置
        ShopkeeperApiEntity entity = appUserApiService.getShopEntity(new Document("company_id", company_id));
        String path = !StringUtil.isBlank(entity.getShare_poster_img()) ? entity.getShare_poster_img() :
                WXConfig.UPLOAD + "qrcode/share_my_qrcode.png"; // 底图地址
        InputStream filePath = ImageUtil.urlToIs(path);
        Image backgroundImg = ImageIO.read(filePath); // 背景图片 流

        // 背景 + 二维码
        File qrcode_file = new File(qrcode_file_path);
        Image qrcode = ImageIO.read(qrcode_file);
        BufferedImage image = ImageUtil.pictureSynthesis(qrcode, backgroundImg, 300, 680);
        image = ImageUtil.pictureAddText("长按识别二维码", image, "宋体", 0, Color.black, 15, 320, 830);

        InputStream imageInput = null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, suffix, os);
            imageInput = new ByteArrayInputStream(os.toByteArray());
        } catch (IOException e) {
        }

        // 海报路径
        String poster = "qrcode" + File.separator + "poster";
        String posterPath = WXConfig.UPLOADFILE + poster;
        String poster_path_location = posterPath + File.separator + user_id + suffix;

        // 保存到本地 - 海报
        File poster_file = new File(poster_path_location);
        ImageUtil.savePic(imageInput, posterPath, user_id + suffix);
        ImageIO.write(image, "png", poster_file);

        // 将生成的二维码上传到OSS
        String ossPath = "qrcode/user/" + user_id + suffix;
        WeiXinOssUtil.getWeiXinOssUtil().importFile(poster_path_location, ossPath);
        String resultPath = ConstantProperties.WQ_FILE_HOST + ossPath;
        // 删除本地 二维码 释放空间
        qrcode_file.delete();
        // 删除本地 海报 释放空间
        poster_file.delete();
        return ApiResUtil.buildRes(true, "招募合伙人二维码", resultPath);
    }

    @Log("修改用户信息")
    @PostMapping("/user/update-user")
    public ApiResponseEntity updateUser(@RequestBody @Validated AppUserUpdateApiVO vo) {
        return appUserApiService.updateUser(vo);
    }

    @Log("用户账号密码登录")
    @PostMapping("/user/login")
    public ApiResponseEntity userLogin(@RequestBody @Validated AppUserLoginVO vo) {
        return appUserApiService.userLogin(vo);
    }

    /**
     * 将图片写入到磁盘
     */
    public static void writeImageToDisk() throws IOException {
        String path = "https://oss-ad.whtianshi.com/qrcode/qrcodeBgi.png"; // 底图地址
        InputStream is = ImageUtil.urlToIs(path);
        Image backgroundImg = ImageIO.read(is); // 背景图片 流

        InputStream is_c = ImageUtil.urlToIs("https://oss-ad.whtianshi.com/4/mall/17EF2E3C28FE3185CCF82B41BE246B99.png");
        // 2.1 背景 + 商品图
        Image commodity_qrcode_img = ImageUtil.upImgWidthAndHeight(ImageIO.read(is_c), 800, 800);
        BufferedImage image = ImageUtil.pictureSynthesis(commodity_qrcode_img, backgroundImg, 30, 110);

        ImageIO.write(image, "jpg", new File("D:\\qrcode\\poster\\i.png"));
    }

    public static void main(String[] args) throws IOException {
        String title = "免年费：抖音网红美食店口碑支付5折，免年费：抖音网红美食店口碑支付5折";
        String result = "";
        if (title.length() > 12) {
            do {
                result += title.substring(0, 12);
                title = title.substring(12);
            } while (title.length() > 12);
            if (title.length() > 0) {
                result += title;
            }
            System.out.println(result);
        }
    }

    /**
     * 获得商品图片
     *
     * @param entity
     * @return
     */
    private String getImage(CardCommodityApiEntity entity) {
        if (!StringUtils.isBlank(entity.getCover_url())) {
            // 如果有封面图，直接返回封面图
            return entity.getCover_url();
        }
        // 没有则取详情图
        for (CardCommodityApiEntity.LinkEntity linkEntity : entity.getLink_url()) {
            if (!StringUtil.isBlank(linkEntity.getUrl())) {
                return linkEntity.getUrl();
            }
        }
        return "";
    }

    /**
     * 获得商品图片
     *
     * @param entity
     * @return
     */
    private String getImage(CommodityApiEntity entity) {
        if (!StringUtils.isBlank(entity.getCover_url())) {
            // 如果有封面图，直接返回封面图
            return entity.getCover_url();
        }
        // 没有则取详情图
        for (CommodityApiEntity.Link linkEntity : entity.getLink_url()) {
            if (!StringUtil.isBlank(linkEntity.getUrl())) {
                return linkEntity.getUrl();
            }
        }
        return "";
    }

    /**
     * 是否显示水印
     * 标识：水印
     *
     * @return
     */
    @GetMapping("user/show-watermark/{company_id}")
    public ApiResponseEntity showWatermark(@PathVariable("company_id") int company_id) {
        Map<String,Object> resultMap = new HashedMap();
        // 是否显示苹果登录
        resultMap.put("appleLogin", false);
        // 是否显示定制化内容，小程序、ios发布版本时许多内容需要屏蔽
        resultMap.put("showCustomization", false);
        // 是否显示水印
        return ApiResUtil.buildRes(true, "魂斗啰啰测试版", resultMap);
    }
}
